import React, { Component } from 'react'
import {nanoid} from 'nanoid'
import PropTypes from 'prop-types'
import './index.css'

export default class Header extends Component {
	//对传入的props进行限制
	static propTypes = {
		addTodo:PropTypes.func.isRequired
	}
	render() {
		return (
			<div className="todo-header">
				<input type="text" placeholder="请输入你的任务名称，按回车键确认" onKeyUp={this.handleKeyUp}/>
			</div>
		)
	}
	//添加todo的回调
	handleKeyUp = (event)=>{
		//获取键盘码、用户的输入
		let {keyCode,target:{value}} = event
		//判断是否是回车按键
		if(keyCode !== 13) return
		if(!value.trim()) return alert('输入不能为空！')
		//将用户的输入包装成一个todo对象
		const todoObj = {
			id:nanoid(),
			title:value,
			done:false
		}
		//通知App添加一个todo
		this.props.addTodo(todoObj)
		//清空用户输入
		event.target.value = ''
	}
}
